﻿#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QSerialPort>
#include <QVector>
#include <QLabel>
#include <QtCharts>
#include <QChartView>
#include <QSerialPortInfo>
#include <QLineEdit>

QT_CHARTS_USE_NAMESPACE

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_connectButton_clicked();
    void on_disconnectButton_clicked();
    void updateSensorData();
    void on_intervalSlider_valueChanged(int value);
    void on_readAddressButton_clicked();
    void on_changeAddressButton_clicked();

private:
    Ui::MainWindow *ui;
    QSerialPort *serialPort;
    QTimer *dataTimer;
    quint8 currentAddress;

    // 实时数据标签
    QVector<QLabel*> dataLabels;

    // 图表组件
    QChart *temperatureChart;
    QChartView *chartView;
    QLineSeries *temperatureSeries;
    QValueAxis *axisX;
    QValueAxis *axisY;

    // 历史数据存储
    QVector<double> temperatureHistory;
    QVector<double> humidityHistory;
    QVector<double> pressureHistory;
    QVector<double> windSpeedHistory;

    // Modbus通信方法
    quint16 calculateCRC(const QByteArray &data);
    QByteArray sendCommand(const QByteArray &command, int expectedLength, int timeout = 200);
    QMap<QString, double> readAllSensors(quint8 address);
    quint8 readDeviceAddress();
    bool changeDeviceAddress(quint8 newAddress);

    // UI更新方法
    void updateDataDisplay(const QMap<QString, double> &data);
    void updateChart();
    void updateStatus(const QString &message, bool isError = false);
};

#endif // MAINWINDOW_H
